<?php
namespace Com\Pay;

//欧创支付宝支付

class OuchuangAlipaySM{

    private $config = array();

    /*
     *
     *
     *    'merchno' => 'A20000000000101',
                'key' => '3CDC66A54DCDE3156AG8B850218B50G7',
                'mch_id' => '100850000428112',
     *
     *
     * */

    public function __construct($send_data){
        $this->config = $send_data;
    }

    /*生成支付连接*/
    public function getUrl($order_info,$other = array()){
        /* 获取提交的订单交易金额 */
        $price = $other['pay_money'];
        /* 获取提交的后台回调地址 */
        $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'].'/Api/NotifyCallback/OuchuangAlipaySMPay';
        $order_sn = $order_info['order_number'];
        $post_data = array(
            "sp_id" => $this->config['appid'],
            "mch_id" => $this->config['mch_id'],
            "org_id" => "10000095",
            "subject" => 'Changbao',
            "out_trade_no" => $order_sn,
            "total_fee" => $price * 100, // 单位：分
            "body" => "OuchuangAlipay",
            "notify_url" => $notifyUrl,
            "return_url" => $order_info['return_url'],
            "nonce_str" => $this->getNonceStr(13) // 随机生成不重复的字符串
        );

        $post_data['sign'] = $this->setSign($post_data,$this->config['mch_key'],false);
        $tar_url = 'http://ouchuang.xjoyt.com:8099/OuYaZhiFu/oytalipay.action?';
        $res = $this->curl_post($tar_url,$post_data);
        $res = json_decode($res,true);
        return $res['qrcode'];
    }

    // 生成签名方法
    private function setSign($data,$skey,$Is_Notify){
        if($Is_Notify){
            $strMd5 = strtoupper(md5('status=' . $data['status'] . '&statusMessage=' . $data['statusMessage'] . '&transactionId=' . $data['transactionId']  . '&mchtId=' . $data['mchtId'] . '&totalamt=' . $data['totalamt'] . '&resultCode=' . $data['resultCode'] . '&resultMsg='. $data['resultMsg'] . '&key=' . $skey));
            return $strMd5;
        }

        // 垃圾接口没签名

// "merchno=" + merchno + "&mch_id=" + mch_id + "&notify_url=" + notify_url + "&nonce_str=" + nonce_str + "&org_id=" +
        // org_id + "&orderTime=" + orderTime + "&out_trade_no=" + out_trade_no + "&return_url=" + return_url + "&show_url=" + show_url +
        //"&subject=" + subject + "&total_fee=" + total_fee;

//        $Mysign = strtoupper(md5('merchno=' . $data['merchno'] . '&mch_id=' . $data['mch_id'] . '&notify_url=' . $data['notify_url']  . '&nonce_str=' . $data['nonce_str'] . '&org_id=' . $data['org_id'] . '&orderTime=' . $data['orderTime'] . '&out_trade_no='. $data['out_trade_no'] . '&return_url=' . $data['return_url'] . '&show_url=' . $data['show_url'] . '&subject=' . $data['subject'] .'&total_fee=' . $data['total_fee'] .'&key=' . $this->config['key']));
        $Mysign = '195ed7bf27d6a5a551b0f3dd7b961b28';
        return $Mysign;
    }


    //回调方法，把返回数据处理成统一规定返回
    public function response($data){
        $Mysign = $this->setSign($data,$this->config['mch_key'],true);
        if($Mysign === $data['sign']){
            if($data['status'] == '0' && $data['resultCode'] == '000000'){
                return true;
            }else{
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }

    function getNonceStr($length = 32)
    {
        $chars = "0123456789abcdef";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return str_shuffle($str);
    }


    public function curl_json_post($url,$data)
    {
        if(is_array($data)){
            $data_string = json_encode($data);
        }else{
            $data_string = $data;
        }
        $ch = curl_init($url);
        // curl_setopt($ch, CURLOPT_TIMEOUT,5);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        $result = curl_exec($ch);
        curl_close ( $ch );
        return $result;
    }

    public function curl_post($url, $data){
        $data = http_build_query($data);
        // file_put_contents('./tmp.txt',$data);
        //echo '<br>'.$data.'<br>';
        // mb_strlen($str,'utf-8');
        // var_dump((mb_strlen($data,'utf-8') == strlen($data)));
        $opts = array(
            'http'=>array(
                'method'=>"POST",
                'timeout'=>60,
                'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
                    "Content-length:".mb_strlen($data,'utf-8')."\r\n" .
                    "Cookie: foo=bar\r\n" .
                    "\r\n",
                'content' => $data,
            )
        );
        $cxContext = stream_context_create($opts);
        $result = file_get_contents($url, false, $cxContext);
        return $result;
    }

    private function gbkToUtf8($arr){
        if(is_array($arr)){
            $res = array();
            foreach($arr as $k => $v){
                $res[$k] = $this->gbkToUtf8($v);
            }
            return $res;
        }else{
            return mb_convert_encoding ( $arr, "UTF-8", "GBK" );
        }
    }


}
